﻿using FolderCompare.ViewModels;
using Prism.Events;
using System.Windows.Media;

namespace FolderCompare.Views;

public partial class MainWindow : Window
{
    public MainWindow(IEventAggregator aggregator)
    {
        InitializeComponent();
        WindowController.UpdateWindowConfig(this, this.GetType());
        this.Loaded += (s, e) =>
        {
            var scroll1 = FindVisualChildren<ScrollViewer>(LeftList).First();
            var scroll2 = FindVisualChildren<ScrollViewer>(RightList).First();
            scroll1.ScrollChanged += (s, e) =>
            {
                scroll2.ScrollToVerticalOffset(scroll1.VerticalOffset);
            };
            scroll2.ScrollChanged += (s, e) =>
            {
                scroll1.ScrollToVerticalOffset(scroll2.VerticalOffset);
            };
        };
        aggregator.GetEvent<ShowMainWindowEvent>().Subscribe(OnShowWindow, ThreadOption.UIThread);
    }

    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject? depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);

                if (child != null && child is T chi)
                    yield return chi;

                foreach (T childOfChild in FindVisualChildren<T>(child))
                    yield return childOfChild;
            }
        }
    }

    private void OnShowWindow()
    {
        this.Show();
        if (this.WindowState == WindowState.Minimized)
        {
            this.WindowState = WindowState.Maximized;
        }
        this.Activate();
    }
}